package com.thd.springboottest.security.service;


import com.thd.springboottest.security.entity.Permissions;
import com.thd.springboottest.security.entity.Role;
import com.thd.springboottest.security.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * com.thd.springboottest.security.service.UserService
 *
 * @author: wanglei62
 * @DATE: 2022/6/21 17:51
 **/
@Component
public class UserServiceImpl implements UserService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    private Map<String,User> mobileUserMap = new HashMap<String,User>();
    private Map<String,User> usernameUserMap = new HashMap<String,User>();;
    public UserServiceImpl(){
        Permissions permissions1 = new Permissions("1","query");
        Permissions permissions2 = new Permissions("2","add");
        Permissions permissions3 = new Permissions("3","del");
        Permissions permissions4 = new Permissions("4","sys:*");

        Set<Permissions> permissionsSet1 = new HashSet<>();
        Set<Permissions> permissionsSet2 = new HashSet<>();

        permissionsSet1.add(permissions1);
        permissionsSet1.add(permissions2);
        permissionsSet1.add(permissions3);
        permissionsSet1.add(permissions4);

        permissionsSet2.add(permissions1);

        // 角色 admin
        Role role = new Role("1","ROLE_admin",permissionsSet1);
        Set<Role> roleSet = new HashSet<>();
        roleSet.add(role);

        // 角色 user
        Role role1 = new Role("2","ROLE_user",permissionsSet2);
        Set<Role> roleSet1 = new HashSet<>();
        roleSet1.add(role1);



        // 第一个用户 wsl 123456
        User user = new User("1","wsl","123456","13800138000",roleSet);
        // 第二个用户 zhangsan 123456
        User user1 = new User("2","zhangsan","123456","13800138001",roleSet1);

        mobileUserMap.put(user.getPhone(), user);
        mobileUserMap.put(user1.getPhone(), user1);

        usernameUserMap.put(user.getUserName(),user);
        usernameUserMap.put(user1.getUserName(),user1);

    }


    @Override
    public User loadUserByAccount(String account) {
        //模拟数据库查询，正常情况此处是从数据库或者缓存查询。
        return getMapByName(account);
    }

    @Override
    public User loadUserByPhone(String phone) {
        //模拟数据库查询，正常情况此处是从数据库或者缓存查询。
        return getMapByPhone(phone);
    }




    /**
     * 模拟数据库查询
     * @param userName
     * @return
     */
    private User getMapByName(String userName){
        return usernameUserMap.get(userName);
    }


    /**
     * 模拟数据库查询
     * @param phone
     * @return
     */
    public User getMapByPhone(String phone){
        return mobileUserMap.get(phone);
    }
}
